// Copyright 2007 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package lichen.components;

import lichen.components.base.AbstractLayout;
import lichen.entities.user.User;
import lichen.internal.services.UserServiceImpl;

import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Cookies;
import org.springframework.orm.hibernate3.HibernateTemplate;


/**
 * 用户控制面板的布局
 * @author <a href=mailto:xiafei114@gmail.com>xiafei114</a>
 * @version $Revision: 225 $
 * @since 0.0.3
 */
public class ControlLayout extends AbstractLayout{
	
	@Inject
	private Cookies cookies;
	@Inject
	private HibernateTemplate _template;
	
	/**
	 * 是否登录.
	 * @return 是否登录.
	 */
	public boolean isLogin(){
		String userId = cookies.readCookieValue(UserServiceImpl.LICHEN_USER_ID_COOKIE_NAME);
		if(userId != null){
			 User user = (User) _template.get(User.class, userId);
			 if(user==null){
				 cookies.removeCookieValue(UserServiceImpl.LICHEN_USER_ID_COOKIE_NAME);
			 }
			 return user!=null;
		}
		return false;
	}
	public User getUser(){
		if(isLogin()){
			String userId = cookies.readCookieValue(UserServiceImpl.LICHEN_USER_ID_COOKIE_NAME);
			User user = (User) _template.get(User.class, userId);
			return user;
		}else{
			throw new RuntimeException("invalid request");
		}
	}
}
